<template>
    <div>
        <div class="e-table" style="background-color: #fff; padding-bottom: 0">
            <!-- 头部buttons -->
            <div class="top" style="margin-bottom: 10px">
                <div class="left" style="width: 100%">
                    <div>
                        <!-- @click="openNewPage('tenderList')" -->
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="importList"
                            v-if="canAddDel"
                            >引入清单</el-button
                        >
                        <el-select
                            v-model="detailsDataCurDtlId"
                            placeholder="请选择包件"
                            style="width: 300px; margin-left: 10px"
                            @change="handleNodeClick"
                        >
                            <el-option
                                v-for="item in detailsData"
                                :key="item.dtlId"
                                :label="item.itemNo + ' ' + item.name"
                                :value="item.dtlId"
                            >
                            </el-option>
                        </el-select>
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="importList2"
                            v-if="Secret"
                            >目标预算引入</el-button
                        >
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="importList3"
                            v-if="Secret"
                            >非生产性开支引入</el-button
                        >
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="importList4"
                            v-if="Secret"
                            >101-1-a</el-button
                        >
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="printMap1"
                            v-if="Secret"
                            >打印tableData</el-button
                        >
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="printMap"
                            v-if="Secret"
                            >打印mapTableData</el-button
                        >
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="printMap2"
                            v-if="Secret"
                            >打印cloneMapInitTableData</el-button
                        >
                        <el-button
                            size="small"
                            class="btn-greenYellow"
                            @click="printMap3"
                            v-if="Secret"
                            >打印wholeListData</el-button
                        >
                        <el-button size="small" class="btn-greenYellow" @click="save" v-if="Secret"
                            >保存</el-button
                        >
                        <el-button size="small" class="btn-greenYellow" @click="save2" v-if="Secret"
                            >保存2</el-button
                        >
                    </div>
                </div>
                <div class="right" style="min-width: 164px">
                    <span style="display: flex; align-items: center; margin-right: 10px">
                        <div style="width: 20px; height: 20px; background: #06ad36"></div>
                        新增
                    </span>
                    <span style="display: flex; align-items: center; margin-right: 10px">
                        <div style="width: 20px; height: 20px; background: #ff2300"></div>
                        删除
                    </span>
                    <span style="display: flex; align-items: center">
                        <div style="width: 20px; height: 20px; background: #ffa40d"></div>
                        修改
                    </span>
                </div>
            </div>
        </div>
        <div class="ruleMessage" v-if="ruleMessage">
            {{ ruleMessage }}
        </div>
        <div class="e-tree-table2">
            <!-- 房屋租赁 -->
            <el-table
                ref="tableRef"
                border
                style="width: 100%"
                row-key="listId"
                :data="tableData"
                :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren'
                }"
                :load="onload"
                lazy
                :row-class-name="tableRowClassName"
                :key="refIndex || dtlIndex"
                @row-click="rowClick"
                @cell-mouse-enter="cellMouseEnter"
                v-if="dtl && dtl.tenderType === 1 && tableRefState"
                :max-height="$store.state.tableHeight"
                v-sortTable="{ tableData: tableData, _this: this, ref: 'tableRef' }"
            >
                <el-table-column label="操作" width="200">
                    <template slot-scope="{ row }">
                        <div class="oparation_box">
                            <!-- <img
                                src="@/assets/btn/sub.png"
                                class="add_sub"
                                @click="addChilden(row, levelIsTotal(row))"
                                title="添加子级"
                                v-if="
                                    (row.isListLeaf || row.label === '项') &&
                                    canAddDel
                                "
                            /> -->
                            <i
                                class="el-icon-delete"
                                style="font-size: 24px; color: #e9513e"
                                @click="onDelNode(row)"
                                title="删除"
                                v-if="canAddDel"
                            ></i>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="code" label="细目编号" min-width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.code"
                            placeholder="请输入内容"
                            v-if="row.label === '项' && canAddDel"
                        ></el-input>
                        <span v-else>{{ row.code }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="codeName"
                    label="细目名称"
                    min-width="150"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.codeName"
                            placeholder="请输入内容"
                            v-if="row.label === '项' && canAddDel"
                        ></el-input>
                        <span v-else>{{ row.codeName }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="label" label="标识" width="150">
                    <!-- <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.subitemName"
                                    placeholder="请输入内容"
                                    v-if="row.inputState"
                                ></el-input>
                                <span v-else>{{ row.subitemName }}</span>
                            </template> -->
                </el-table-column>
                <el-table-column
                    prop="structureNamePaths"
                    label="结构部位名称"
                    width="150"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="{ row }">
                        <span>{{ row.structureNamePaths }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="计量单位" width="100">
                    <template slot-scope="{ row }">
                        <el-select
                            v-model="row.unit"
                            placeholder="请选择"
                            v-if="row.label === '项'"
                        >
                            <el-option
                                v-for="item in unitMeasure"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                        <span v-else>{{ row.unit }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="priceType" label="单价类型" width="130">
                            <template slot-scope="{ row }">
                                <el-select
                                    v-model="row.priceType"
                                    placeholder="请选择"
                                    v-if="row.isListLeaf"
                                >
                                    <el-option label="全单价" :value="1"></el-option>
                                    <el-option label="劳务单价" :value="2"></el-option>
                                </el-select>
                            </template>
                        </el-table-column> -->
                <el-table-column prop="num" label="数量" width="130">
                    <template
                        slot-scope="{ row }"
                        v-if="row.isListLeaf || row.isLeaf || row.isAllLeaf || row.structurePaths"
                    >
                        <el-input
                            v-model="row.num"
                            placeholder="请输入内容"
                            v-if="row.structureNamePaths && !levelIsTotal(row) && canEdit"
                            v-enterFloat2Neg="{
                                set: row,
                                key: 'num'
                            }"
                            @input="numBlur(row)"
                        ></el-input>
                        <span v-else>{{ isNaN(row.num) ? 0 : row.num }}</span>
                        <i
                            slot="suffix"
                            class="el-icon-tickets"
                            @click="showHistory(row, 'numUpdateHistory')"
                            v-if="row.numUpdateHistory && row.numUpdateHistory.length !== 0"
                        ></i>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="单价" width="130">
                    <!-- :disabled="!row.children && !levelIsTotal(row)" -->
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.price"
                            placeholder="请输入内容"
                            v-if="row.isLeaf && canEdit && !levelIsTotal(row)"
                            v-enterFloatNeg="{
                                set: row,
                                key: 'price'
                            }"
                            :disabled="!row.children && !levelIsTotal(row)"
                            @input="priceBlur(row)"
                        ></el-input>
                        <span v-else>{{ row.price }}</span>
                        <i
                            slot="suffix"
                            class="el-icon-tickets"
                            @click="showHistory(row, 'priceUpdateHistory')"
                            v-if="row.priceUpdateHistory && row.priceUpdateHistory.length !== 0"
                        ></i>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="金额(元)" width="100">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.amount"
                            placeholder="请输入内容"
                            v-if="row.unit === '总额' && canEdit"
                            v-enterAllInteger1
                            @input="amountBlur(row)"
                        ></el-input>
                        <span v-else>{{ row.amount }}</span>
                        <i
                            slot="suffix"
                            class="el-icon-tickets"
                            @click="showHistory(row, 'amountUpdateHistory')"
                            v-if="row.amountUpdateHistory && row.amountUpdateHistory.length !== 0"
                        ></i>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 非生产性开支 -->
            <el-table
                v-else
                ref="tableRef"
                border
                style="width: 100%"
                row-key="listId"
                :data="tableData"
                :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren'
                }"
                :load="onload"
                lazy
                :row-class-name="tableRowClassName"
                :key="refIndex || dtlIndex"
                @row-click="rowClick"
                @cell-mouse-enter="cellMouseEnter"
                :max-height="$store.state.tableHeight"
                v-sortTable="{ tableData: tableData, _this: this, ref: 'tableRef' }"
            >
                <el-table-column label="操作" width="200">
                    <template slot-scope="{ row }">
                        <div class="oparation_box">
                            <img
                                src="@/assets/btn/sub.png"
                                class="add_sub"
                                @click="addChilden2(row, levelIsTotal(row))"
                                title="添加子级"
                                v-if="canAddDel"
                            />
                            <i
                                class="el-icon-delete"
                                style="font-size: 24px; color: #e9513e"
                                @click="onDelNode(row)"
                                title="删除"
                                v-if="canAddDel"
                            ></i>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="code" label="细目编号" min-width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.code"
                            placeholder="请输入内容"
                            v-if="canAddDel"
                        ></el-input>
                        <span v-else>{{ row.code }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="codeName"
                    label="细目名称"
                    min-width="150"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.codeName"
                            placeholder="请输入内容"
                            v-if="canAddDel"
                        ></el-input>
                        <span v-else>{{ row.codeName }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="num" label="数量" width="130">
                    <template slot-scope="{ row }" v-if="row.isLeaf === 1">
                        <el-input
                            v-model="row.num"
                            placeholder="请输入内容"
                            v-if="row.isLeaf === 1 && canEdit"
                            v-enterFloat2Neg="{
                                set: row,
                                key: 'num'
                            }"
                            @input="numBlur2(row)"
                        ></el-input>
                        <span v-else>{{ row.num === 0 ? '' : row.num }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="单价" width="130">
                    <!-- :disabled="!row.children && !levelIsTotal(row)" -->
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.price"
                            placeholder="请输入内容"
                            v-if="row.isLeaf === 1 && canEdit"
                            v-enterFloatNeg="{
                                set: row,
                                key: 'price'
                            }"
                            @input="priceBlur2(row)"
                        ></el-input>
                        <span v-else>{{ row.price === 0 ? '' : row.price }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="金额(元)" width="100">
                    <!-- <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.amount"
                                    placeholder="请输入内容"
                                    v-if="canEdit"
                                    v-enterAllInteger1
                                    @blur="amountBlur(row)"
                                ></el-input>
                                <span v-else>{{ row.amount }}</span>
                            </template> -->
                </el-table-column>
            </el-table>
        </div>
        <!-- dialog -->
        <el-dialog :visible.sync="historyDialogVisible" width="70%">
            <el-table
                :data="historyTableData"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                border
                default-expand-all
                :max-height="$store.state.tableHeight"
                ref="table"
                v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
            >
                <el-table-column prop="modifier" label="修改人" width="200"> </el-table-column>
                <el-table-column prop="createTime" label="修改时间" width="100"> </el-table-column>
                <el-table-column prop="originalContent" label="原数据" width="100">
                </el-table-column>
                <el-table-column prop="modifiedContent" label="修改后数据" width="100">
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="historyDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
// import applyRequest from '@/api/tender/apply.js'
import engineeringOtherRequest from '@/api/tender/engineeringOther.js'
// import tenderRequest from '@/api/tender/tender.js'
import {
    // eslint-disable-next-line no-unused-vars
    toLocation,
    vueDom,
    selectDataClient,
    // eslint-disable-next-line no-unused-vars
    openAppClient,
    getItemOfTreeArr
} from '@/utils/common.js'
import { uidBuilder } from '@/api/base/uid.js'
// eslint-disable-next-line no-unused-vars
import { mapMutations, mapState, mapActions } from 'vuex'
// import leaseSetAddVue from '../../../settlementManagement/equipmentBilling/leaseSet/leaseSetAdd.vue'

export default {
    props: {
        // 包件数据
        detailsData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 清单数据
        tableData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 审核状态
        auditState: {
            type: Object,
            default: function () {
                return {}
            }
        }
    },
    model: {
        prop: 'tableData',
        event: 'change'
    },
    computed: {
        ...mapState({
            unitMeasure: state => state.biddingApplication.dictionaries.unitMeasure //计量单位
        }),
        tenderId () {
            return this.$route.query.billid
        },
        // 当前选择包件的index
        dtlIndex () {
            return this.detailsData.findIndex(item => this.dtlId === item.dtlId)
        },
        // 当前清单对应的包件
        dtl () {
            return this.detailsData.find(item => this.dtlId === item.dtlId)
        },
        // 审核中不能增删
        canAddDel () {
            if (this.auditState?.canModify === false || Object.keys(this.auditState).length === 0) {
                return false
            } else {
                return true
            }
        },
        // 审核完成后不能修改
        canEdit () {
            if (Object.keys(this.auditState).length === 0) {
                return false
            } else {
                return true
            }
        }
    },
    watch: {
        // 包件数据
        detailsData: {
            handler (newVal) {
                // 处理数据获得包件列表
                if (newVal.length === 0) {
                    this.$emit('change', [])
                    // this.tableData = []
                    this.dtlId = ''
                    this.detailsDataCurDtlId = ''
                } else {
                    // 如果没选择过包件，包件id就默认第一个
                    if (this.dtlId === '' && this.selectDetailState === false) {
                        this.dtlId = newVal[0].dtlId
                    } else {
                        // 寻找当前包件数据里是否有当前id（主要判断被删情况）
                        const findVal = newVal.find(item => item.dtlId === this.dtlId)
                        if (findVal) {
                            this.dtlId = findVal.dtlId
                        } else {
                            this.dtlId = ''
                        }
                    }
                }
                if (newVal.length === 1) {
                    setTimeout(() => {
                        $('.el-tree-node:first')?.addClass('is-current')
                    }, 100)
                }
            },
            deep: true
        },
        // 当前选择的包件id
        dtlId (newVal) {
            this.detailsDataCurDtlId = newVal
            if (
                newVal !== '' &&
                JSON.stringify(this.tableData[this.dtlIndex]) ===
                    JSON.stringify(this.cloneTableData[this.dtlIndex])
            ) {
                this.getData() // 获取清单数据
                // && this.dtl.tenderType === 1
                if (this.dtl) {
                    this.getAllData() // 获取清单全部数据（已选功能）
                }
            }
            if (newVal === '') {
                this.tableData = []
            }
        },
        tableData: {
            handler (newVal) {
                if (newVal.loadState === true) return
                console.log('执行333')
                this.ifEdit()
                // 计算招标限价
                this.allTableData[this.dtlIndex] = newVal
            },
            deep: true
        },
        mapTableData: {
            handler (newVal) {
                // console.log('watch mapTableData', newVal)
                this.allMapTableData[this.dtlIndex] = newVal
            },
            deep: true
        },
        // deleteTableData: {
        //     handler (newVal) {
        //         // console.log('watch mapTableData', newVal)
        //         this.allDeleteTableData[this.dtlIndex] = newVal
        //     },
        //     deep: true
        // },
        wholeListData: {
            handler (newVal) {
                // console.log('watch mapTableData', newVal)
                this.allWholeListData[this.dtlIndex] = newVal
            },
            deep: true
        },
        'dtl.tenderType' () {
            this.refIndex++
        }
    },
    data () {
        return {
            detailsOfProposedArr: [],
            // tableData: [],
            cloneTableData: [],
            mapTableData: {},
            // deleteTableData: [],
            addList: [], // 缓存新增数据
            structure: [], // 结构部位
            temp: [],
            count: 0,
            dtlId: '',
            allTableData: [],
            allMapTableData: [],
            // allDeleteTableData: [],
            Secret: false,
            ruleMessage: '',
            cloneMapInitTableData: {},
            startEndStake: '', // 起止桩号
            refIndex: 0, // 切换招标类型需要重置table组件，否则会有缓存bug
            wholeListData: {}, // 当前包件对应清单的所有数据（已选功能）
            allWholeListData: [],
            tableRefState: true,
            detailsDataCurDtlId: '',
            selectDetailState: false,
            historyTableData: [],
            historyDialogVisible: false
        }
    },
    created () {
        // this.getData()
        // this.findByApplyId()
        // this.importList()
        this.setUnitMeasur()
    },
    mounted () {
        vueDom(
            // 默认0为选中项
            () => {
                $('.el-tree-node:first')?.addClass('is-current')
            },
            () => {
                return $('.el-tree-node:first')?.attr('class')?.includes('is-current')
            }
        )
        const temp = []
        document.onkeydown = e => {
            temp.push(e.keyCode)
            if (temp.length > 4) {
                temp.splice(0, 1)
            }
            if (temp.join('') === '38384040') {
                this.Secret = true
                document.onkeydown = undefined
            }
        }
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setSelectedInfo']),
        ...mapActions('biddingApplication', ['setUnitMeasur']),
        printMap1 () {
            console.log(this.tableData)
        },
        printMap () {
            console.log(this.mapTableData)
        },
        printMap2 () {
            console.log(this.cloneMapInitTableData)
        },
        printMap3 () {
            console.log(this.wholeListData)
        },
        rowClick (row) {
            console.log('row', row)
        },
        showHistory (row, arg) {
            this.historyDialogVisible = true
            this.historyTableData = row[arg]
        },
        // eslint-disable-next-line no-unused-vars
        cellMouseEnter (row, column, cell, event) {
            if (!row.packageId) return
            this.$bus.$emit('setDtlId', row.packageId)
        },
        ifEdit () {
            console.log('执行了ifEdit')
            const temp = JSON.parse(JSON.stringify(this.allMapTableData))
            temp.map(async item => {
                if (item === null) return
                const arrMap = Object.values(item)
                arrMap.forEach(item => {
                    if (!item.listId) return
                    // 判断是否有修改的行（补遗可能要在watch做）
                    const wholeListData = Object.values(this.wholeListData).filter(
                        item => item.listId
                    )
                    if (wholeListData.length !== 0) {
                        let initData = this.cloneMapInitTableData[item.listId]
                        let itemData = ''
                        if (this.dtl.tenderType === 1) {
                            if (!item.listId || !item.label) return
                        }
                        if (this.dtl.tenderType === 1) {
                            initData =
                                JSON.stringify(initData?.code) +
                                JSON.stringify(initData?.codeName) +
                                JSON.stringify(initData?.priceType) +
                                JSON.stringify(initData?.num) +
                                JSON.stringify(initData?.price) +
                                JSON.stringify(initData?.amount)
                            itemData =
                                JSON.stringify(item?.code) +
                                JSON.stringify(item?.codeName) +
                                JSON.stringify(item?.priceType) +
                                JSON.stringify(item?.num) +
                                JSON.stringify(item?.price) +
                                JSON.stringify(initData?.amount)
                        } else {
                            initData =
                                JSON.stringify(initData?.num) +
                                JSON.stringify(initData?.price) +
                                JSON.stringify(initData?.amount)
                            itemData =
                                JSON.stringify(item?.num) +
                                JSON.stringify(item?.price) +
                                JSON.stringify(item?.amount)
                        }
                        console.log('initData', initData)
                        console.log('itemData', itemData)
                        if (
                            initData &&
                            itemData !== initData &&
                            item.changeType !== -1 &&
                            item.changeType !== 1
                        ) {
                            const _item = this.mapTableData[item.listId]
                            console.log('_item', _item)
                            // 判断金额、数量、单价是否修改
                            if (item.amount != this.cloneMapInitTableData[item.listId].amount) {
                                item.isUpdateAmountState = true
                            } else {
                                item.isUpdateAmountState = false
                            }
                            if (item.num != this.cloneMapInitTableData[item.listId].num) {
                                item.isUpdateNumState = true
                            } else {
                                item.isUpdateNumState = false
                            }
                            if (item.price != this.cloneMapInitTableData[item.listId].price) {
                                item.isUpdatePriceState = true
                            } else {
                                item.isUpdatePriceState = false
                            }
                            // 如果不是删除状态
                            if (item.changeType !== -1 && item.changeType !== -2) {
                                _item.changeType = 2
                                // 如果后端状态不是1
                                if (item.state !== 1) {
                                    _item.state = 2
                                }
                            }
                            // wholeListData也要做改变，已选数据需要
                            if (this.wholeListData[item.listId]) {
                                this.wholeListData[item.listId].changeType = 2
                            }
                        }
                    }
                })
                let tenderType = null
                if (this.dtl) {
                    tenderType = this.dtl.tenderType
                }
                let res = []
                // 房屋租赁、征地拆迁
                if (tenderType === 1) {
                    // 去除结构部位
                    res = arrMap.filter(item => item.label)
                    // // 删除数据也要去除结构部位
                    // if (this.allDeleteTableData[index]) {
                    //     this.allDeleteTableData[index] = this.allDeleteTableData[index].filter(
                    //         item => item.label
                    //     )
                    // }
                    res.forEach(item => {
                        // 项的结构都是初始数据，需要替换成children
                        // if (item.label === '项') {
                        if (item.applyStructureList) {
                            item.applyStructureList = JSON.parse(JSON.stringify(item.children))
                        }
                        // 去除children
                        delete item.children
                        // 只有最子级有部位
                        if (item.isLeaf === 0) {
                            delete item.applyStructureList
                        }
                    })
                    // 非生产性开支
                } else {
                    res = arrMap
                    // 去除虚拟节点0
                    res = arrMap.filter(item => item.listId)
                    res.forEach(item => {
                        // 去除children
                        delete item.children
                    })
                }
                // if (this.allDeleteTableData[index] === undefined) {
                //     this.allDeleteTableData[index] = []
                // }
                // res = [...res, ...this.allDeleteTableData[index]]
                // mapData可能和deleteData重复
                // let filterArr = []
                // res = res.filter(item => {
                //     if (filterArr.includes(item.listId)) return false
                //     filterArr.push(item.listId)
                //     return true
                // })
                // 1
                if (Object.keys(this.mapTableData).length !== 0) {
                    // console.log('res', res)
                    console.log('111')
                    await engineeringOtherRequest.changeDtlCreate(res)
                }
                // num++
                // if (num === length) {
                //     resolve()
                // }
            })
        },
        getAllData (packageId = this.dtlId) {
            console.log('执行了1')
            this.wholeListData = {}
            engineeringOtherRequest.getAllListByPackageId({ packageId }).then(res => {
                res.forEach(item => {
                    // wholeListData也需要children
                    item.children = []
                    res.forEach(item2 => {
                        if (item.listId === item2.parentId) {
                            item.children.push(item2)
                        }
                    })
                    // 最子级
                    if (item.isLeaf === 1) {
                        res.forEach(item2 => {
                            if (item2.parentId === item.listId) {
                                item.applyStructureList = []
                                // 增加结构（客户端返显）
                                item.applyStructureList.push(JSON.parse(JSON.stringify(item2)))
                            }
                        })
                    }
                    this.wholeListData[item.listId] = item
                    this.wholeListData[item.listId].changeState = 0
                    this.saveCloneMap(item)
                })
                this.wholeListData[0] = {
                    children: Object.values(this.wholeListData)
                }
            })
        },
        async handleNodeClick (dtlId) {
            const item = this.detailsData.find(item2 => item2.dtlId === dtlId)
            this.selectDetailState = true
            this.dtlId = item.dtlId
            if (this.allTableData[this.dtlIndex] !== undefined) {
                await this.$emit('change', this.allTableData[this.dtlIndex])
                // this.tableData = this.allTableData[this.dtlIndex]
            } else {
                await this.$emit('change', [])
                // this.tableData = []
            }
            if (this.allMapTableData[this.dtlIndex] !== undefined) {
                this.mapTableData = this.allMapTableData[this.dtlIndex]
            } else {
                this.mapTableData = {}
            }
            // if (this.allDeleteTableData[this.dtlIndex] !== undefined) {
            //     this.deleteTableData = this.allDeleteTableData[this.dtlIndex]
            // } else {
            //     this.deleteTableData = []
            // }
            if (this.allWholeListData[this.dtlIndex] !== undefined) {
                this.wholeListData = this.allWholeListData[this.dtlIndex]
            } else {
                this.wholeListData = {}
            }
            // console.log('allTableData', this.allTableData)
            // console.log('allMapTableData', this.allMapTableData)
        },
        async getData (parenId = '0') {
            const res = await engineeringOtherRequest.inventoryGetByPackageId({
                packageId: this.dtlId,
                parentId: parenId
            })
            // 房屋租赁
            if (this.dtl.tenderType === 1) {
                res.forEach(item => {
                    item.changeType = 0
                    // 处理懒加载
                    if (item.isAllLeaf === 0) {
                        item.hasChildren = true
                    }
                    if (item.price === 0) {
                        item.price = ''
                    }
                    // 结构层不返billId
                    if (item.billId === null) {
                        item.billId = item.subitemId
                        item.deleteState = 0
                    }
                    this.mapTableData[item.listId] = item
                    this.mapTableData[item.listId] = item
                })
            } else {
                // 非生产性开支
                res.forEach(item => {
                    item.changeType = 0
                    if (item.isLeaf === 0) {
                        item.hasChildren = true
                    }
                    if (item.price === 0) {
                        item.price = ''
                    }
                    this.mapTableData[item.listId] = item
                })
            }
            if (parenId === '0') {
                await this.$emit('change', res)
                this.$set(this.mapTableData, '0', {
                    children: this.tableData
                })
            }
            this.cloneTableData[this.dtlIndex] = JSON.parse(JSON.stringify(res))
            return res
        },
        // 根据ID获取该节点的对象
        getIdNode (list, id) {
            for (let i in list) {
                if (list[i].listId == id) {
                    return [list[i]]
                }
                if (list[i].children) {
                    let node = this.getIdNode(list[i].children, id)
                    if (node !== undefined) {
                        return node
                    }
                }
            }
        },
        // 初始化计算
        initCalNum (str) {
            const arrMapValues = Object.values(this.mapTableData)
            console.log('arrMapValues', arrMapValues)
            const arr = []
            const lastIds = arrMapValues
                .filter(item =>
                    str === 'num' ? item.structurePaths || item.isListLeaf : item.structurePaths
                )
                .filter(item => {
                    if (!arr.includes(item.parentId)) {
                        arr.push(item.parentId)
                        return item
                    }
                })
            lastIds.forEach(item => {
                this.recurCount({
                    parentId: item.parentId,
                    rootId: '0',
                    listField: 'listId',
                    parentField: 'parentId',
                    item,
                    str,
                    type: str === 'num' ? 'float' : 'int'
                })
            })
        },
        // 初始化计算（非生产性开支）
        initCalNum2 (str) {
            const arrMapValues = Object.values(this.mapTableData)
            console.log('arrMapValues', arrMapValues)
            // const arr = []
            const lastIds = arrMapValues.find(item => item.isLeaf)
            console.log('lastIds', lastIds)
            this.recurCount({
                parentId: lastIds.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                lastIds,
                str,
                type: str === 'num' ? 'float' : 'int'
            })
        },
        // 顶级是否是总额
        levelIsTotal (row) {
            const levels = getItemOfTreeArr(this.tableData, 'listId', row.listId)
            if (levels.find(item => item.unit === '总额') === undefined) {
                return false
            } else {
                return true
            }
        },
        // 记录进cloneMap
        saveCloneMap (row) {
            if (!this.cloneMapInitTableData[row.listId]) {
                this.cloneMapInitTableData[row.listId] = JSON.parse(JSON.stringify(row))
            }
        },
        // 金额修改
        amountBlur (row) {
            row.amount = parseFloat(row.amount)
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row,
                str: 'amount'
            })
            // 总额向下修改
            if (row.unit === '总额') {
                while (row.children) {
                    row.children.forEach(item => {
                        item.amount = row.amount
                    })
                    row = row.children
                }
            }
        },
        // 数量修改
        numBlur (row) {
            // if (row.num === '') {
            //     row.num = 0
            // }
            // row.price = isNaN(parseFloat(row.price)) ? 0 : parseFloat(row.price)
            // row.num = isNaN(parseFloat(row.num)) ? 0 : parseFloat(row.num)
            // 计算本行金额
            row.amount = Math.round(row.price * row.num)
            // 修改父级applyStructureList里的值
            // this.mapTableData[row.parentId].applyStructureList =
            //     this.mapTableData[row.parentId].children
            // 向上汇总数量
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row,
                str: 'num',
                type: 'float'
            })
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row,
                str: 'amount'
            })
        },
        // 单价修改
        priceBlur (row) {
            // if (row.price === '') {
            //     row.price = 0
            // }
            // if (!row.children && !this.levelIsTotal(row)) return
            // row.price = isNaN(parseFloat(row.price)) ? 0 : parseFloat(row.price)
            row.num = isNaN(parseFloat(row.num)) ? 0 : parseFloat(row.num)
            // 向下修改
            row.children.forEach(item => {
                item.price = row.price
                this.$set(this.mapTableData, item.listId, item)
                // this.mapTableData[item.listId] = item
            })
            // 向上修改
            if (row.label === '项') {
                const listId = row.parentId
                const levelNodes = getItemOfTreeArr(this.tableData, 'listId', listId)
                levelNodes.forEach(item => {
                    item.price = ''
                    this.$set(this.mapTableData, item.listId, item)
                    // this.mapTableData[item.listId] = item
                })
            }
            // 计算当前行金额
            row.amount = Math.round(row.price * row.num)
            // 计算子金额（单价会改变子级）
            let temp = row.children
            while (temp) {
                temp.forEach(item => {
                    item.amount = Math.round(item.price * item.num)
                    this.$set(this.mapTableData, item.listId, item)
                    // this.mapTableData[item.listId] = item
                })
                temp = temp.children ? temp.children : null
            }
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row,
                str: 'amount'
            })
        },
        // 数量修改(非生产性开支引入)
        numBlur2 (row) {
            if (row.num === '') {
                row.num = 0
            }
            row.price = isNaN(parseFloat(row.price)) ? 0 : parseFloat(row.price)
            row.num = isNaN(parseFloat(row.num)) ? 0 : parseFloat(row.num)
            // 计算本行金额
            row.amount = Math.round(row.price * row.num)
            // 修改父级applyStructureList里的值
            // this.mapTableData[row.parentId].applyStructureList =
            //     this.mapTableData[row.parentId].children
            // 向上汇总数量
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row,
                str: 'num',
                type: 'float'
            })
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row,
                str: 'amount'
            })
        },
        // 单价修改(非生产性开支引入)
        priceBlur2 (row) {
            console.log('row', row)
            if (row.price === '') {
                row.price = 0
            }
            // if (!row.children && !this.levelIsTotal(row)) return
            row.price = isNaN(parseFloat(row.price)) ? 0 : parseFloat(row.price)
            row.num = isNaN(parseFloat(row.num)) ? 0 : parseFloat(row.num)
            // 向下修改
            // row.children.forEach(item => {
            //     item.price = row.price
            //     this.$set(this.mapTableData, item.listId, item)
            //     // this.mapTableData[item.listId] = item
            // })
            // 向上修改
            // if (row.label === '项') {
            const listId = row.parentId
            const levelNodes = getItemOfTreeArr(this.tableData, 'listId', listId)
            levelNodes.forEach(item => {
                item.price = ''
                this.$set(this.mapTableData, item.listId, item)
                // this.mapTableData[item.listId] = item
            })
            // }
            // 计算当前行金额
            row.amount = Math.round(row.price * row.num)
            // 计算子金额（单价会改变子级）
            let temp = row.children
            while (temp) {
                temp.forEach(item => {
                    item.amount = Math.round(item.price * item.num)
                    this.$set(this.mapTableData, item.listId, item)
                    // this.mapTableData[item.listId] = item
                })
                temp = temp.children ? temp.children : null
            }
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row,
                str: 'amount'
            })
        },
        tenderListRule () {
            if (this.tableData.length === 0) {
                this.ruleMessage = '请添加清单'
                this.$emit('onChangeTab', { name: 'tenderListCon' })
                return false
            }
            const ruleMessageArr = new Set()
            // console.log('this.mapTableData', this.mapTableData)
            Object.values(this.mapTableData).forEach(item => {
                // 顶级不需要遍历
                if (!item.listId) return
                if (item.changeState === -1) return
                let name = item.code
                    ? '细目编号-' + item.code
                    : '结构部位名称-' + item.structureNamePaths
                if (name === '结构部位名称-undefined') {
                    name = '项'
                }
                // 项需要填写细目编号
                if (item.label === '项' && item.changeState !== -1) {
                    if (!item.code) {
                        ruleMessageArr.add(`${name}请填写细目编号`)
                    }
                }
                // 项需要填写细目名称
                if (item.label === '项' && item.changeState !== -1) {
                    if (!item.codeName) {
                        ruleMessageArr.add(`${name}请填写细目名称`)
                    }
                }
                // 清单最明细层要填单价类型
                // if (item.isListLeaf === 1) {
                //     if (!item.priceType) {
                //         ruleMessageArr.add('请选择单价类型')
                //     }
                // }
                // 最明细级要填单价
                if (item.isLeaf === 1 && item.unit !== '总额' && item.changeState !== -1) {
                    if (!item.price) {
                        ruleMessageArr.add(`${name}请填写单价`)
                    }
                }
                // 结构层要填数量
                if (item.structurePaths && item.changeState !== -1) {
                    if (item.num === '') {
                        ruleMessageArr.add(`${name}请填写数量`)
                    }
                }
            })
            this.ruleMessage = [...ruleMessageArr].join('，')
            if (this.ruleMessage !== '') {
                this.$emit('onChangeTab', { name: 'tenderListCon' })
                return false
            } else {
                return true
            }
        },
        async save () {
            console.log('000')
            if (this.allMapTableData.length === 0) return Promise.resolve()
            console.log('111')
            // if (!this.tenderListRule()) {
            //     this.$emit('onChangeTab', { name: 'tenderList' })
            //     return Promise.reject()
            // }
            // new Promise(resolve => {
            // let num = 0
            // const length = this.detailsData.length
            // 保存数据不改变原table
            const temp = JSON.parse(JSON.stringify(this.allMapTableData))
            await Promise.all(
                temp.map(async item => {
                    if (item === null) return
                    const arrMap = Object.values(item)
                    arrMap.forEach(item => {
                        if (!item.listId) return
                        // 判断是否有修改的行（补遗可能要在watch做）
                        const wholeListData = Object.values(this.wholeListData).filter(
                            item => item.listId
                        )
                        if (wholeListData.length !== 0) {
                            let initData = this.cloneMapInitTableData[item.listId]
                            let itemData = ''
                            if (this.dtl.tenderType === 1) {
                                if (!item.listId || !item.label) return
                            }
                            if (this.dtl.tenderType === 1) {
                                initData =
                                    JSON.stringify(initData?.code) +
                                    JSON.stringify(initData?.codeName) +
                                    JSON.stringify(initData?.priceType) +
                                    JSON.stringify(initData?.num) +
                                    JSON.stringify(initData?.price) +
                                    JSON.stringify(initData?.amount)
                                itemData =
                                    JSON.stringify(item?.code) +
                                    JSON.stringify(item?.codeName) +
                                    JSON.stringify(item?.priceType) +
                                    JSON.stringify(item?.num) +
                                    JSON.stringify(item?.price) +
                                    JSON.stringify(initData?.amount)
                            } else {
                                initData =
                                    JSON.stringify(initData?.num) +
                                    JSON.stringify(initData?.price) +
                                    JSON.stringify(initData?.amount)
                                itemData =
                                    JSON.stringify(item?.num) +
                                    JSON.stringify(item?.price) +
                                    JSON.stringify(item?.amount)
                            }
                            console.log('initData', initData)
                            console.log('itemData', itemData)
                            if (
                                initData &&
                                itemData !== initData &&
                                item.changeType !== -1 &&
                                item.changeType !== 1
                            ) {
                                // 判断金额、数量、单价是否修改
                                if (item.amount != this.cloneMapInitTableData[item.listId].amount) {
                                    item.isUpdateAmountState = true
                                } else {
                                    item.isUpdateAmountState = false
                                }
                                if (item.num != this.cloneMapInitTableData[item.listId].num) {
                                    item.isUpdateNumState = true
                                } else {
                                    item.isUpdateNumState = false
                                }
                                if (item.price != this.cloneMapInitTableData[item.listId].price) {
                                    item.isUpdatePriceState = true
                                } else {
                                    item.isUpdatePriceState = false
                                }
                                item.changeType = 2
                                // wholeListData也要做改变，已选数据需要
                                if (this.wholeListData[item.listId]) {
                                    this.wholeListData[item.listId].changeType = 2
                                }
                            }
                        }
                    })
                    let tenderType = null
                    if (this.dtl) {
                        tenderType = this.dtl.tenderType
                    }
                    let res = []
                    // 房屋租赁、征地拆迁
                    if (tenderType === 1) {
                        // 去除结构部位
                        res = arrMap.filter(item => item.label)
                        // // 删除数据也要去除结构部位
                        // if (this.allDeleteTableData[index]) {
                        //     this.allDeleteTableData[index] = this.allDeleteTableData[index].filter(
                        //         item => item.label
                        //     )
                        // }
                        res.forEach(item => {
                            // 项的结构都是初始数据，需要替换成children
                            // if (item.label === '项') {
                            if (item.applyStructureList) {
                                item.applyStructureList = JSON.parse(JSON.stringify(item.children))
                            }
                            // 去除children
                            delete item.children
                            // 只有最子级有部位
                            if (item.isLeaf === 0) {
                                delete item.applyStructureList
                            }
                        })
                        // 非生产性开支
                    } else {
                        res = arrMap
                        // 去除虚拟节点0
                        res = arrMap.filter(item => item.listId)
                        res.forEach(item => {
                            // 去除children
                            delete item.children
                        })
                    }
                    // if (this.allDeleteTableData[index] === undefined) {
                    //     this.allDeleteTableData[index] = []
                    // }
                    // res = [...res, ...this.allDeleteTableData[index]]
                    // mapData可能和deleteData重复
                    // let filterArr = []
                    // res = res.filter(item => {
                    //     if (filterArr.includes(item.listId)) return false
                    //     filterArr.push(item.listId)
                    //     return true
                    // })
                    // 1
                    if (Object.keys(this.mapTableData).length !== 0) {
                        // console.log('res', res)
                        console.log('111')
                        await engineeringOtherRequest.changeDtlCreate(res)
                    }
                    // num++
                    // if (num === length) {
                    //     resolve()
                    // }
                })
            ).then(() => {
                // this.cloneTableData = []
                this.mapTableData = {}
                // // this.deleteTableData = []
                // this.addList = []
                // this.allTableData = []
                // this.allMapTableData = []
                // // this.allDeleteTableData = []
                this.cloneMapInitTableData = {}
                this.tableData = []
                this.getData()
                // && this.dtl.tenderType === 1
                if (this.dtl) {
                    this.getAllData()
                }
            })
        },
        async save2 () {
            const temp = JSON.parse(JSON.stringify(this.allMapTableData))
            await Promise.all(
                temp.map(async (item, index) => {
                    index
                    let res = Object.values(item)
                    res.forEach(item => {
                        // 去除children
                        delete item.children
                    })
                    // if (this.allDeleteTableData[index] === undefined) {
                    //     this.allDeleteTableData[index] = []
                    // }
                    // res = [...res, ...this.allDeleteTableData[index]]
                    // mapData可能和deleteData重复
                    let filterArr = []
                    res = res.filter(item => {
                        if (filterArr.includes(item.listId)) return false
                        filterArr.push(item.listId)
                        return true
                    })
                    res.forEach(item => {
                        // applyStructureList给deleteState初始值
                        if (item.applyStructureList) {
                            item.applyStructureList.forEach(item => {
                                item.deleteState = item.deleteState ? item.deleteState : 0
                                // mapStartEndStake[item.billId] = item
                            })
                        }
                        // 判断是否有修改的行（补遗可能要在watch做）
                        if (Object.keys(this.wholeListData).length !== 0) {
                            let initData = this.cloneMapInitTableData[item.listId]
                            initData =
                                JSON.stringify(initData?.code) +
                                JSON.stringify(initData?.codeName) +
                                JSON.stringify(initData?.priceType) +
                                JSON.stringify(initData?.num) +
                                JSON.stringify(initData?.price) +
                                JSON.stringify(initData?.amount)
                            const itemData =
                                JSON.stringify(item?.code) +
                                JSON.stringify(item?.codeName) +
                                JSON.stringify(item?.priceType) +
                                JSON.stringify(item?.num) +
                                JSON.stringify(item?.price) +
                                JSON.stringify(item?.amount)
                            if (
                                initData &&
                                itemData !== initData &&
                                item.changeState !== -1 &&
                                item.changeState !== 1
                            ) {
                                item.changeState = 2
                                // wholeListData也要做改变，已选数据需要
                                if (this.wholeListData[item.listId]) {
                                    this.wholeListData[item.listId].changeState = 2
                                }
                            }
                        }
                    })
                    res = res.filter(item => Object.keys(item).length !== 0 && item.billId)
                    console.log('res', res)
                    if (Object.keys(this.mapTableData).length !== 0) {
                        await engineeringOtherRequest.otherDtlSave(res)
                    }
                })
                // console.log('temp', temp)
            ).then(() => {
                // this.cloneTableData = []
                this.mapTableData = {}
                // // this.deleteTableData = []
                // this.addList = []
                // this.allTableData = []
                // this.allMapTableData = []
                // // this.allDeleteTableData = []
                this.cloneMapInitTableData = {}
                this.tableData = []
                this.getData()
                // && this.dtl.tenderType === 1
                if (this.dtl) {
                    this.getAllData()
                }
            })
        },
        // 生成结构部位
        async addStructure (row, parentId) {
            // 结构的初始数据
            console.log('addStructure', row)
            const temp = JSON.parse(JSON.stringify(row.applyStructureList))
            console.log('temp', temp)
            const uid = await this.uidBuilder({ num: temp.length }, 'arr')
            if (row.children[0].label !== '项') {
                console.log('子不是项')
                temp.forEach((item, index) => {
                    item.listId = uid[index]
                    item.parentId = parentId
                    item.price = row.price
                    item.num = row.num
                    this.$set(this.mapTableData, item.listId, item)
                    // this.mapTableData[item.listId] = item
                })
            } else {
                console.log('子是项')
                temp.forEach((item, index) => {
                    item.listId = uid[index]
                    item.parentId = parentId
                    item.price = 0
                    item.num = 0
                    this.$set(this.mapTableData, item.listId, item)
                    // this.mapTableData[item.listId] = item
                })
            }
            return temp
        },
        // 导入后的changeState
        importChangeState (item) {
            const wholeListDataArr = Object.values(this.wholeListData)
            // 如果wholeListData长度为0，说明是第1次引入数据，为新增1
            if (wholeListDataArr.length === 0) {
                return 1
            } else {
                // 如果wholeListData没有的id，表示新增
                if (!this.wholeListData[item.thisLevelId]) {
                    return 1
                } else {
                    // 如果wholeListData的changeState是2
                    if (this.wholeListData[item.thisLevelId].changeState === 2) {
                        return 2
                    } else {
                        return 0
                    }
                }
            }
        },
        // 后端需要的字段（目标预算）
        arrFieldConvert (arr, cloneMapTableData) {
            const res = []
            // await Promise.all(
            arr.map(async (item, index) => {
                res.push({
                    amount: 0,
                    applyStructureList: item.structure.length !== 0 ? item.structure : [],
                    billId: this.tenderId,
                    changeType: this.importChangeState(item),
                    code: '', // 细目编码
                    codeName: '', // 细目名称
                    isAllLeaf: 0, // 是否所有最子级
                    isLeaf: 0,
                    isListLeaf: 0, // 是否是清单最子级
                    isUpdateAmountState: false,
                    isUpdateNumState: false,
                    isUpdatePriceState: false,
                    label: '', // 标识
                    listId: '', // 本级id
                    num: 0, // 数量
                    packageId: this.dtlId,
                    parentId: '', // 	父级ID
                    price: '',
                    // priceType: '',
                    // recordId: '',
                    unit: '', // 计量单位
                    targetBudgetListId: '' // 目标预算清单id
                })
                // 处理成后端要的结构数据
                if (res[index].applyStructureList.length === 0) {
                    delete res[index].applyStructureList
                } else {
                    // const uid = await this.uidBuilder(
                    //     {
                    //         num: res[index].applyStructureList.length
                    //     },
                    //     'arr'
                    // )
                    res[index].applyStructureList.forEach(item => {
                        item.listId = item.thisLevelId
                        item.num = item.quantity
                        item.price = 0
                        item.amount = 0
                        item.deleteState = 0
                        delete item.isDetailed
                        delete item.structureName
                        delete item.thisLevelId
                        delete item.quantity
                    })
                }
                res[index].label = item.identification
                res[index].isListLeaf = item.termIsDetailed
                res[index].isAllLeaf = 0
                res[index].isLeaf = item.isDetailed
                res[index].codeName = item.itemName
                res[index].code = item.itemNo
                res[index].parentId = item.parentId
                res[index].num = item.quantity
                res[index].unit = item.unit
                res[index].listId = item.thisLevelId
                res[index].targetBudgetListId = item.billId
            })
            // 选择的数据对比之前数据，如果有还是使用之前数据
            if (cloneMapTableData !== undefined) {
                res.forEach((item, index) => {
                    if (cloneMapTableData[item.listId]) {
                        res[index].code = cloneMapTableData[item.listId].code
                        res[index].codeName = cloneMapTableData[item.listId].codeName
                        res[index].structureNamePaths =
                            cloneMapTableData[item.listId].structureNamePaths
                        res[index].unit = cloneMapTableData[item.listId].unit
                        // res[index].priceType = cloneMapTableData[item.listId].priceType
                        res[index].num = cloneMapTableData[item.listId].num
                        res[index].price = cloneMapTableData[item.listId].price
                        // res[index].materialPrice = cloneMapTableData[item.listId].materialPrice
                        // res[index].lossRate = cloneMapTableData[item.listId].lossRate
                        // res[index].materialPriceLoss =
                        //     cloneMapTableData[item.listId].materialPriceLoss
                        // res[index].equipmentPrice = cloneMapTableData[item.listId].equipmentPrice
                        // res[index].otherPrice = cloneMapTableData[item.listId].otherPrice
                        // res[index].subtotal = cloneMapTableData[item.listId].subtotal
                        res[index].amount = cloneMapTableData[item.listId].amount
                        // res[index].rule = cloneMapTableData[item.listId].rule
                        // if(item.applyStructureList) {
                        //     item.applyStructureList.forEach(item=>{
                        //         item.amount = cloneMapTableData[item.listId].amount
                        //     })
                        // }
                    }
                })
            }
            return res
        },
        // 后端需要的字段（非生产性开支）
        _arrFieldConvert (arr) {
            const res = []
            arr.map((item, index) => {
                res.push({
                    amount: 0,
                    // applyStructureList: item.structure.length !== 0 ? item.structure : [],
                    billId: this.tenderId,
                    changeType: 1,
                    code: '', // 细目编码
                    codeName: '', // 细目名称
                    isAllLeaf: 0, // 是否所有最子级
                    isLeaf: 0, // 是否最子级
                    isListLeaf: 0, // 是否是清单最子级
                    isUpdateAmountState: false,
                    isUpdateNumState: false,
                    isUpdatePriceState: false,
                    label: '', // 标识
                    listId: '', // 本级id
                    num: 0, // 数量
                    packageId: this.dtlId,
                    parentId: '', // 	父级ID
                    price: '',
                    // priceType: '',
                    // recordId: '',
                    unit: '' // 计量单位
                })
                // 处理成后端要的结构数据
                // res[index].label = item.identification
                // res[index].isListLeaf = item.termIsDetailed
                // res[index].isAllLeaf = 0
                res[index].isLeaf = item.isLeaf
                res[index].codeName = item.costItem
                res[index].code = item.unproductiveNo
                res[index].parentId = item.parentId
                res[index].num = item.qty
                // res[index].unit = item.unit
                res[index].listId = item.listId
                res[index].price = item.noTaxPrice
                res[index].amount = item.noTaxSubTotal
            })
            return res
        },
        // 数组转树
        arrToTree (arr) {
            const rootId = arr[0].parentId
            const res = []
            const map = arr.reduce((res, v) => ((res[v.listId] = v), res), {})
            for (const item of arr) {
                // 添加结构
                if (item.applyStructureList) {
                    item.children = JSON.parse(JSON.stringify(item.applyStructureList))
                }
                if (item.parentId === rootId) {
                    res.push(item)
                    continue
                }
                if (item.parentId in map) {
                    const parent = map[item.parentId]
                    parent.children = parent.children || []
                    parent.children.push(item)
                }
            }
            return res
        },
        // 树转数组
        treeToArr (tree) {
            return tree.reduce(
                (arr, { id, title, pid, children = [] }) =>
                    arr.concat([{ id, title, pid }], this.treeToArr(children)),
                []
            )
        },
        // 结构层转换客户端要的数据
        structureConver (applyStructureList) {
            const temp = []
            applyStructureList.forEach((item, index) => {
                temp.push({
                    billId: '',
                    budgetPrice: 0,
                    identification: null,
                    isDetailed: null,
                    itemName: null,
                    itemNo: null,
                    materialPrice: 0,
                    parentId: '',
                    quantity: 0,
                    structureName: '',
                    structureNamePaths: '',
                    structurePaths: '',
                    termIsDetailed: null,
                    thisLevelId: '',
                    unit: null,
                    structure: null
                })
                temp[index].billId = item.targetBudgetListId || null
                temp[index].budgetPrice = item.budgetPrice || null
                temp[index].identification = item.label || null
                temp[index].isDetailed = item.isLeaf || null
                temp[index].itemName = item.codeName || null
                temp[index].itemNo = item.code || null
                temp[index].materialPrice = item.materialPrice || null
                temp[index].parentId = item.parentId || null
                temp[index].quantity = item.num || null
                temp[index].structureName = item.structureName || null
                temp[index].structureNamePaths = item.structureNamePaths || null
                temp[index].structurePaths = item.structurePaths || null
                temp[index].termIsDetailed = item.isListLeaf || null
                temp[index].thisLevelId = item.listId || null
                temp[index].unit = item.unit || null
            })
            return temp
        },
        // 后端数据转成客户端要的数据
        arrFieldConvert2 (selectedData) {
            if (selectedData.length === 0) return []
            let temp = []
            selectedData.forEach((item, index) => {
                temp.push({
                    billId: '',
                    budgetPrice: null,
                    identification: '',
                    isDetailed: 0,
                    itemName: '',
                    itemNo: '',
                    materialPrice: null,
                    parentId: '',
                    quantity: null,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 0,
                    thisLevelId: '',
                    unit: '',
                    structure: []
                })
                temp[index].billId = item.targetBudgetListId || null
                temp[index].budgetPrice = item.budgetPrice || null
                temp[index].identification = item.label || null
                temp[index].isDetailed = item.isLeaf || null
                temp[index].itemName = item.codeName || null
                temp[index].itemNo = item.code || null
                temp[index].materialPrice = item.materialPrice || null
                temp[index].parentId = item.parentId || null
                temp[index].quantity = item.num || null
                temp[index].structureName = item.structureName || null
                temp[index].structureNamePaths = item.structureNamePaths || null
                temp[index].structurePaths = item.structurePaths || null
                temp[index].termIsDetailed = item.isListLeaf || 0
                temp[index].thisLevelId = item.listId || null
                temp[index].unit = item.unit || null
                temp[index].structure = item.applyStructureList
                    ? this.structureConver(item.applyStructureList)
                    : []
            })
            // 过滤掉0级    // 过滤掉结构（已包含在最子集清单里）
            temp = temp.filter(item => item.thisLevelId && item.identification)
            return temp
        },
        // 获取包件列表数据
        async findByApplyId () {
            let data = []
            let leftTree = []
            if (this.detailsOfProposed.length !== 0) {
                data = this.detailsOfProposed
            } else {
                await engineeringOtherRequest
                    .packageListByEntity({
                        limit: 20,
                        page: 1,
                        tenderApplyId: this.tenderId
                    })
                    .then(res => {
                        data = res
                    })
            }
            data.forEach(value => {
                leftTree.push({ label: value.name })
            })
            this.detailsOfProposedArr = leftTree
        },
        // 通过id获取子级数据
        async getById (listId) {
            // （此处为模拟）
            const uid = await this.uidBuilder({ num: 2 })
            // 右侧树列表假数据
            const result = [
                {
                    recordId: '', //记录ID
                    packageId: '123', //包件ID
                    parentId: listId, //父级ID
                    code: uid[0], //细目编码
                    codeName: '123', //细目名称
                    isLeaf: 0, //是否是最明细级
                    hasChildren: true,
                    listId: uid[0], //本级ID
                    subitemName: '123', //分部分项名称
                    subitemId: '123', //分部分项ID
                    budgetName: '123', //预算名称
                    budgetId: '123', //预算id
                    unit: '123', //计量单位
                    num: 123, //数量 默认值为零
                    price: 123, //单价 默认值为零
                    priceType: '123', //单价类型 (劳务单价 全单价) 工程招标特有
                    amount: 123, //金额
                    billId: this.tenderId, //单据Id
                    label: 0, //标识(0,清单，1项，2结构部位)"
                    changeType: 1 //清单变更状态 0未变更 1新增 2编辑 -1删除
                },
                {
                    recordId: '', //记录ID
                    packageId: '123', //包件ID
                    parentId: listId, //父级ID
                    code: uid[1], //细目编码
                    codeName: '123', //细目名称
                    isLeaf: 0, //是否是最明细级
                    hasChildren: true,
                    listId: uid[1], //本级ID
                    subitemName: '123', //分部分项名称
                    subitemId: '123', //分部分项ID
                    budgetName: '123', //预算名称
                    budgetId: '123', //预算id
                    unit: '123', //计量单位
                    num: 123, //数量 默认值为零
                    price: 123, //单价 默认值为零
                    priceType: '123', //单价类型 (劳务单价 全单价) 工程招标特有
                    amount: 123, //金额
                    billId: this.tenderId, //单据Id
                    label: 0, //标识(0,清单，1项，2结构部位)"
                    changeType: 1 //清单变更状态 0未变更 1新增 2编辑 -1删除
                }
            ]
            return result
        },
        saveMapTableData (temp = this.tableData) {
            if (temp === null) return
            this.$set(this.mapTableData, '0', {
                children: this.tableData
            })
            // this.mapTableData['0'] = {
            //     children: this.tableData
            // }
            temp.forEach(item => {
                while (item) {
                    if (item.listId === undefined) break
                    this.$set(this.mapTableData, item.listId, item)
                    // this.mapTableData[item.listId] = item
                    item = item.children ? item.children : null
                    this.saveMapTableData(item)
                }
            })
        },
        // 处理后端id重复bug
        backEndBug (val) {
            const temp = []
            // 结构层的id
            val.forEach(item => {
                item.structure.forEach(item2 => {
                    temp.push(item2.thisLevelId)
                })
            })
            // 子级的id和结构层id相同删除
            val.forEach((item, index) => {
                if (temp.includes(item.thisLevelId)) {
                    delete val[index]
                }
            })
            return val
        },
        // 获取已选节点
        getSelectedIDs () {
            const wholeListDataArr = Object.values(this.wholeListData)
            const mapTableDataArr = Object.values(this.mapTableData)
            if (wholeListDataArr.length === 0) {
                // 如果mapTable为-1，代表删掉了，应该去掉
                for (let i = 0; i < mapTableDataArr.length; i++) {
                    const item = mapTableDataArr[i]
                    const changeState = this.mapTableData[item.listId]?.changeState // 0级没listId
                    if (changeState === -1) {
                        mapTableDataArr.splice(i--, 1)
                    }
                }
                return this.arrFieldConvert2(mapTableDataArr)
            } else {
                // 如果wholeListData为-1，代表删掉了，应该去掉
                for (let i = 0; i < wholeListDataArr.length; i++) {
                    const item = wholeListDataArr[i]
                    const changeState = this.wholeListData[item.listId]?.changeState // 0级没listId
                    if (changeState === -1) {
                        wholeListDataArr.splice(i--, 1)
                    }
                }
                return this.arrFieldConvert2(wholeListDataArr)
            }
        },
        importList () {
            // console.log('this.dtl', this.dtl)
            if (this.dtlId === '') {
                this.clientPop('err', '请先添加包件')
                return
            }
            // 获取已选节点
            const SelectedIDs = this.getSelectedIDs()
            console.log('SelectedIDs', SelectedIDs)
            const tenderType = this.dtl.tenderType
            selectDataClient({
                SelectServiceToken:
                    tenderType === 1 ? 'EngineerSelectorImportDetail' : '/project/up/getDtlByOrgId', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify(SelectedIDs),
                Title: '选择清单' // 标题
            }).then(async val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                // 备份一个对比选择数据是否包含已有数据
                const cloneMapTableData = JSON.parse(JSON.stringify(this.mapTableData))
                //  如果没选数据
                if (val.length === 0) {
                    // 重置
                    this.cloneTableData = []
                    this.mapTableData = {}
                    // this.deleteTableData = []
                    this.addList = []
                    this.cloneMapInitTableData = {}
                    this.tableData = []
                    return
                }
                // 目标预算引入
                if (this.dtl && this.dtl.tenderType === 1) {
                    // 处理客户端重复数据
                    val = this.backEndBug(val)
                    // 转换前端显示数据
                    // arrFieldConvert changeState会在此时定义
                    await this.$emit(
                        'change',
                        this.arrToTree(this.arrFieldConvert(val, cloneMapTableData))
                    )
                    // 重置table，不然table展开时数据不刷新
                    // this.tableRefState = false
                    // setTimeout(() => {
                    //     this.tableRefState = true
                    // }, 0)
                    this.refIndex++
                    this.saveMapTableData()
                    // 用来对比的初始数据
                    // val.forEach(item => {
                    //     this.saveCloneMap(item)
                    // })
                    // 做完对比再置空
                    this.wholeListData = {}
                    // 初始化计算数量
                    // this.initCalNum('num')
                } else {
                    // 非生产性开支引入
                    if (this.tableData.length === 0) {
                        await this.$emit('change', this.arrToTree(this._arrFieldConvert(val)))
                    } else {
                        // 导入的节点转为树
                        let addValArrTree = this.arrToTree(this._arrFieldConvert(val))
                        // 去除与原数相同listId的节点
                        for (let i = 0; i < addValArrTree.length; i++) {
                            const item = addValArrTree[i]
                            const delObj = this.tableData.find(
                                item2 => item2.listId === item.listId
                            )
                            if (delObj) {
                                addValArrTree.splice(i--, 1)
                            }
                        }
                        this.tableData.push(...addValArrTree)
                    }
                    // 重置table，不然table展开时数据不刷新
                    // this.tableRefState = false
                    // setTimeout(() => {
                    //     this.tableRefState = true
                    // }, 0)
                    this.refIndex++
                    this.saveMapTableData()
                    // 用来对比的初始数据
                    // const temp = this.arrFieldConvert(val)
                    // temp.forEach(item => {
                    //     this.saveCloneMap(item)
                    // })
                    // // 做完对比再置空
                    // this.wholeListData = {}
                    // 初始化金额
                    this.initCalNum2('amount')
                }
            })
        },
        // 目标预算引入
        async importList2 () {
            console.log('this.dtlId', this.dtlId)
            if (this.dtlId === '') {
                this.clientPop('err', '请先添加包件')
                return
            }
            // 测试数据1
            var val = [
                {
                    billId: '1556535464307650562',
                    budgetPrice: null,
                    identification: '清单',
                    isDetailed: 0,
                    itemName: '总则',
                    itemNo: '100章',
                    materialPrice: null,
                    parentId: '0',
                    quantity: null,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 0,
                    thisLevelId: '532d7b1909dd3821255584641a9be44f',
                    unit: '',
                    structure: []
                },
                {
                    billId: '1556535466639683586',
                    budgetPrice: null,
                    identification: '清单',
                    isDetailed: 0,
                    itemName: '通则',
                    itemNo: '101',
                    materialPrice: null,
                    parentId: '532d7b1909dd3821255584641a9be44f',
                    quantity: null,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 0,
                    thisLevelId: '335bb55ad650ecb476e32ad7b77b66e4',
                    unit: '',
                    structure: []
                },
                {
                    billId: '1556535466639683587',
                    budgetPrice: null,
                    identification: '清单',
                    isDetailed: 0,
                    itemName: '保险费',
                    itemNo: '101-1',
                    materialPrice: null,
                    parentId: '335bb55ad650ecb476e32ad7b77b66e4',
                    quantity: null,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 0,
                    thisLevelId: 'ab4661bf03e2defc4c09cf0e6525de17',
                    unit: '',
                    structure: []
                },
                {
                    billId: '1556535466639683588',
                    budgetPrice: 100,
                    identification: '清单',
                    isDetailed: 1,
                    itemName: '按合同条款规定，提供建筑工程一切险',
                    itemNo: '101-1-a',
                    materialPrice: null,
                    parentId: 'ab4661bf03e2defc4c09cf0e6525de17',
                    quantity: 1,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 1,
                    thisLevelId: 'd34d521a5adf0fa5ef790ff7aeda314a',
                    unit: '总额',
                    structure: [
                        {
                            billId: '1562256901228130307',
                            budgetPrice: 100,
                            identification: null,
                            isDetailed: null,
                            itemName: null,
                            itemNo: null,
                            materialPrice: null,
                            parentId: 'd34d521a5adf0fa5ef790ff7aeda314a',
                            quantity: 1,
                            structureName: '保险费',
                            structureNamePaths: '总则-通则-保险费',
                            structurePaths:
                                '[{"isLeaf": 0, "listId": "e86399c5d35243c19cfb14174bf34ffc", "parentId": "0", "structureId": "1562256901228130305", "structureNo": "1", "structureName": "总则", "structureType": 0}, {"isLeaf": 0, "listId": "bd05ee67137a4fb093d3ea7cc8376977", "parentId": "e86399c5d35243c19cfb14174bf34ffc", "structureId": "1562256901228130306", "structureNo": "1-1", "structureName": "通则", "structureType": 0}, {"isLeaf": 1, "listId": "7d7f69a67e034cc0a15b9683436ed0d8", "parentId": "bd05ee67137a4fb093d3ea7cc8376977", "structureId": "1562256901228130307", "structureNo": "1-1-1", "structureName": "保险费", "structureType": 0}]',
                            termIsDetailed: null,
                            thisLevelId: '1564143919117824001',
                            unit: null,
                            structure: null
                        }
                    ]
                },
                {
                    billId: '1556535466660655105',
                    budgetPrice: 100,
                    identification: '清单',
                    isDetailed: 1,
                    itemName: '按合同条款规定，提供第三者责任险',
                    itemNo: '101-1-b',
                    materialPrice: null,
                    parentId: 'ab4661bf03e2defc4c09cf0e6525de17',
                    quantity: 1,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 1,
                    thisLevelId: '27033c47a82ff2a70351fd55b782c434',
                    unit: '总额',
                    structure: [
                        {
                            billId: '1562256901228130307',
                            budgetPrice: 100,
                            identification: null,
                            isDetailed: null,
                            itemName: null,
                            itemNo: null,
                            materialPrice: null,
                            parentId: '27033c47a82ff2a70351fd55b782c434',
                            quantity: 1,
                            structureName: '保险费',
                            structureNamePaths: '总则-通则-保险费',
                            structurePaths:
                                '[{"isLeaf": 0, "listId": "e86399c5d35243c19cfb14174bf34ffc", "parentId": "0", "structureId": "1562256901228130305", "structureNo": "1", "structureName": "总则", "structureType": 0}, {"isLeaf": 0, "listId": "bd05ee67137a4fb093d3ea7cc8376977", "parentId": "e86399c5d35243c19cfb14174bf34ffc", "structureId": "1562256901228130306", "structureNo": "1-1", "structureName": "通则", "structureType": 0}, {"isLeaf": 1, "listId": "7d7f69a67e034cc0a15b9683436ed0d8", "parentId": "bd05ee67137a4fb093d3ea7cc8376977", "structureId": "1562256901228130307", "structureNo": "1-1-1", "structureName": "保险费", "structureType": 0}]',
                            termIsDetailed: null,
                            thisLevelId: '1564143919122018305',
                            unit: null,
                            structure: null
                        }
                    ]
                },
                {
                    billId: '1556535466660655106',
                    budgetPrice: 100,
                    identification: '清单',
                    isDetailed: 1,
                    itemName: '施工机具保险费',
                    itemNo: '101-1-c',
                    materialPrice: null,
                    parentId: 'ab4661bf03e2defc4c09cf0e6525de17',
                    quantity: 1,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 1,
                    thisLevelId: '84f18bf431ad20e2aa87cbe97cb30f6a',
                    unit: '总额',
                    structure: [
                        {
                            billId: '1562256901228130307',
                            budgetPrice: 100,
                            identification: null,
                            isDetailed: null,
                            itemName: null,
                            itemNo: null,
                            materialPrice: null,
                            parentId: '84f18bf431ad20e2aa87cbe97cb30f6a',
                            quantity: 1,
                            structureName: '保险费',
                            structureNamePaths: '总则-通则-保险费',
                            structurePaths:
                                '[{"isLeaf": 0, "listId": "e86399c5d35243c19cfb14174bf34ffc", "parentId": "0", "structureId": "1562256901228130305", "structureNo": "1", "structureName": "总则", "structureType": 0}, {"isLeaf": 0, "listId": "bd05ee67137a4fb093d3ea7cc8376977", "parentId": "e86399c5d35243c19cfb14174bf34ffc", "structureId": "1562256901228130306", "structureNo": "1-1", "structureName": "通则", "structureType": 0}, {"isLeaf": 1, "listId": "7d7f69a67e034cc0a15b9683436ed0d8", "parentId": "bd05ee67137a4fb093d3ea7cc8376977", "structureId": "1562256901228130307", "structureNo": "1-1-1", "structureName": "保险费", "structureType": 0}]',
                            termIsDetailed: null,
                            thisLevelId: '1564143919130406914',
                            unit: null,
                            structure: null
                        }
                    ]
                },
                {
                    billId: '1556535466660655107',
                    budgetPrice: 100,
                    identification: '清单',
                    isDetailed: 1,
                    itemName: '雇主责任保险费',
                    itemNo: '101-1-d',
                    materialPrice: null,
                    parentId: 'ab4661bf03e2defc4c09cf0e6525de17',
                    quantity: 1,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 1,
                    thisLevelId: 'db9fba0b191f30b208969d1e9e94bec4',
                    unit: '总额',
                    structure: [
                        {
                            billId: '1562256901228130307',
                            budgetPrice: 100,
                            identification: null,
                            isDetailed: null,
                            itemName: null,
                            itemNo: null,
                            materialPrice: null,
                            parentId: 'db9fba0b191f30b208969d1e9e94bec4',
                            quantity: 1,
                            structureName: '保险费',
                            structureNamePaths: '总则-通则-保险费',
                            structurePaths:
                                '[{"isLeaf": 0, "listId": "e86399c5d35243c19cfb14174bf34ffc", "parentId": "0", "structureId": "1562256901228130305", "structureNo": "1", "structureName": "总则", "structureType": 0}, {"isLeaf": 0, "listId": "bd05ee67137a4fb093d3ea7cc8376977", "parentId": "e86399c5d35243c19cfb14174bf34ffc", "structureId": "1562256901228130306", "structureNo": "1-1", "structureName": "通则", "structureType": 0}, {"isLeaf": 1, "listId": "7d7f69a67e034cc0a15b9683436ed0d8", "parentId": "bd05ee67137a4fb093d3ea7cc8376977", "structureId": "1562256901228130307", "structureNo": "1-1-1", "structureName": "保险费", "structureType": 0}]',
                            termIsDetailed: null,
                            thisLevelId: '1564143919134601217',
                            unit: null,
                            structure: null
                        }
                    ]
                }
            ]
            // 转换前端显示数据
            await this.$emit('change', this.arrToTree(await this.arrFieldConvert(val)))
            console.log('this.tableData', this.tableData)
            this.saveMapTableData()
            // 做完对比再置空
            this.wholeListData = {}
            // 初始化计算数量
            this.initCalNum('num')
        },
        // 非生产性开支引入
        async importList3 () {
            // 测试数据
            var val = [
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '基本费用',
                    dtlId: '1557209915532754946',
                    isLeaf: 0,
                    listId: '1556933149304012802',
                    noTaxPrice: 0,
                    noTaxSubTotal: 24397494,
                    parentId: '0',
                    qty: 0,
                    remark: '',
                    resourceId: '1556933149304012803',
                    unproductiveNo: '1'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '职工薪酬',
                    dtlId: '1557209915532754947',
                    isLeaf: 0,
                    listId: '1556933149304012804',
                    noTaxPrice: 0,
                    noTaxSubTotal: 22106294,
                    parentId: '1556933149304012802',
                    qty: 0,
                    remark: '',
                    resourceId: '1556933149304012805',
                    unproductiveNo: '1-1'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '项目经理',
                    dtlId: '1557209915532754948',
                    isLeaf: 1,
                    listId: '1556933149308207105',
                    noTaxPrice: 12000,
                    noTaxSubTotal: 576000,
                    parentId: '1556933149304012804',
                    qty: 48,
                    remark: '根据项目机构设置及人员配置计划、项目的合同工期按《工程项目管理办法》中“7项目人力资源管理”及公司其他相关制度规定计算',
                    resourceId: '1556933149308207106',
                    unproductiveNo: '1-1-1'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '其他项目班子成员',
                    dtlId: '1557209915532754949',
                    isLeaf: 1,
                    listId: '1556933149312401410',
                    noTaxPrice: 10000,
                    noTaxSubTotal: 1920000,
                    parentId: '1556933149304012804',
                    qty: 192,
                    remark: '根据项目机构设置及人员配置计划、项目的合同工期按《工程项目管理办法》中“7项目人力资源管理”及公司其他相关制度规定计算',
                    resourceId: '1556933149312401411',
                    unproductiveNo: '1-1-2'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '项目一般管理人员',
                    dtlId: '1557209915536949249',
                    isLeaf: 1,
                    listId: '1556933149316595713',
                    noTaxPrice: 8000,
                    noTaxSubTotal: 15360000,
                    parentId: '1556933149304012804',
                    qty: 1920,
                    remark: '',
                    resourceId: '1556933149316595714',
                    unproductiveNo: '1-1-3'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '福利费',
                    dtlId: '1557209915536949250',
                    isLeaf: 1,
                    listId: '1556933149316595715',
                    noTaxPrice: 2400,
                    noTaxSubTotal: 480000,
                    parentId: '1556933149304012804',
                    qty: 200,
                    remark: '每人每年2400元',
                    resourceId: '1556933149316595716',
                    unproductiveNo: '1-1-4'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '工会经费',
                    dtlId: '1557209915536949251',
                    isLeaf: 1,
                    listId: '1556933149320790017',
                    noTaxPrice: 357120,
                    noTaxSubTotal: 357120,
                    parentId: '1556933149304012804',
                    qty: 1,
                    remark: '按工资总额的2%计取，80%上交公司工会',
                    resourceId: '1556933149320790018',
                    unproductiveNo: '1-1-5'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '教育经费',
                    dtlId: '1557209915536949252',
                    isLeaf: 1,
                    listId: '1556933149320790019',
                    noTaxPrice: 267840,
                    noTaxSubTotal: 267840,
                    parentId: '1556933149304012804',
                    qty: 1,
                    remark: '按工资总额的1.5%计取，80%上交公司',
                    resourceId: '1556933149320790020',
                    unproductiveNo: '1-1-6'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '社会保险费',
                    dtlId: '1557209915536949253',
                    isLeaf: 1,
                    listId: '1556933149324984321',
                    noTaxPrice: 2252534,
                    noTaxSubTotal: 2252534,
                    parentId: '1556933149304012804',
                    qty: 1,
                    remark: '指按规定单位应承担的养老、医疗、失业、工伤、生育保险等费用,按岗位工资的25.23%计取',
                    resourceId: '1556933149324984322',
                    unproductiveNo: '1-1-7'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '住房公积金',
                    dtlId: '1557209915536949254',
                    isLeaf: 1,
                    listId: '1556933149329178625',
                    noTaxPrice: 535680,
                    noTaxSubTotal: 535680,
                    parentId: '1556933149304012804',
                    qty: 1,
                    remark: '按规定应由单位承担的岗位工资的6%计取',
                    resourceId: '1556933149329178626',
                    unproductiveNo: '1-1-8'
                },
                {
                    billId: '1557209915268513793',
                    changeType: 0,
                    costItem: '企业年金',
                    dtlId: '1557209915536949255',
                    isLeaf: 1,
                    listId: '1556933149329178627',
                    noTaxPrice: 357120,
                    noTaxSubTotal: 357120,
                    parentId: '1556933149304012804',
                    qty: 1,
                    remark: '按岗位工资的4%计取',
                    resourceId: '1556933149329178628',
                    unproductiveNo: '1-1-9'
                }
            ]
            await this.$emit('change', this.arrToTree(this._arrFieldConvert(val)))
            this.refIndex++
            this.saveMapTableData()
            // 用来对比的初始数据
            val.forEach(item => {
                this.saveCloneMap(item)
            })
            // 做完对比再置空
            this.wholeListData = {}
            // 初始化金额
            this.initCalNum2('amount')
        },
        async importList4 () {
            if (this.dtlId === '') {
                this.clientPop('err', '请先添加包件')
                return
            }
            // 测试数据1
            var val = [
                {
                    billId: '1556535464307650562',
                    budgetPrice: null,
                    identification: '清单',
                    isDetailed: 0,
                    itemName: '总则',
                    itemNo: '100章',
                    materialPrice: null,
                    parentId: '0',
                    quantity: null,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 0,
                    thisLevelId: '532d7b1909dd3821255584641a9be44f',
                    unit: '',
                    structure: []
                },
                {
                    billId: '1556535466639683586',
                    budgetPrice: null,
                    identification: '清单',
                    isDetailed: 0,
                    itemName: '通则',
                    itemNo: '101',
                    materialPrice: null,
                    parentId: '532d7b1909dd3821255584641a9be44f',
                    quantity: null,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 0,
                    thisLevelId: '335bb55ad650ecb476e32ad7b77b66e4',
                    unit: '',
                    structure: []
                },
                {
                    billId: '1556535466639683587',
                    budgetPrice: null,
                    identification: '清单',
                    isDetailed: 0,
                    itemName: '保险费',
                    itemNo: '101-1',
                    materialPrice: null,
                    parentId: '335bb55ad650ecb476e32ad7b77b66e4',
                    quantity: null,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 0,
                    thisLevelId: 'ab4661bf03e2defc4c09cf0e6525de17',
                    unit: '',
                    structure: []
                },
                {
                    billId: '1556535466639683588',
                    budgetPrice: 1000,
                    identification: '清单',
                    isDetailed: 1,
                    itemName: '按合同条款规定，提供建筑工程一切险',
                    itemNo: '101-1-a',
                    materialPrice: 100,
                    parentId: 'ab4661bf03e2defc4c09cf0e6525de17',
                    quantity: 10,
                    structureName: null,
                    structureNamePaths: null,
                    structurePaths: null,
                    termIsDetailed: 1,
                    thisLevelId: 'd34d521a5adf0fa5ef790ff7aeda314a',
                    unit: 'm3',
                    structure: [
                        {
                            billId: '1561638717286445060',
                            budgetPrice: 1000,
                            identification: null,
                            isDetailed: null,
                            itemName: null,
                            itemNo: null,
                            materialPrice: 100,
                            parentId: 'd34d521a5adf0fa5ef790ff7aeda314a',
                            quantity: 10,
                            structureName: '保险费',
                            structureNamePaths: '总则-通则-保险费',
                            structurePaths:
                                '[{"isLeaf": 0, "listId": "98a866b70fb54d49978a960cfc763dde", "parentId": "0", "structureId": "1561638717286445058", "structureNo": "1", "structureName": "总则", "structureType": 0}, {"isLeaf": 0, "listId": "d96bd68a951c4e16a6bce3575a7657e0", "parentId": "98a866b70fb54d49978a960cfc763dde", "structureId": "1561638717286445059", "structureNo": "1-1", "structureName": "通则", "structureType": 0}, {"isLeaf": 1, "listId": "15f427917fd1417e8991a904538315e9", "parentId": "d96bd68a951c4e16a6bce3575a7657e0", "structureId": "1561638717286445060", "structureNo": "1-1-1", "structureName": "保险费", "structureType": 0}]',
                            termIsDetailed: null,
                            thisLevelId: '1564186827791462402',
                            unit: null,
                            structure: null
                        }
                    ]
                }
            ]
            //  如果没选数据
            if (val.length === 0) {
                // 重置
                this.cloneTableData = []
                this.mapTableData = {}
                this.deleteTableData = []
                this.addList = []
                this.cloneMapInitTableData = {}
                this.tableData = []
                return
            }
            // 处理客户端重复数据
            val = this.backEndBug(val)
            // 转换前端显示数据
            // arrFieldConvert changeState会在此时定义
            await this.$emit('change', this.arrToTree(this.arrFieldConvert(val)))
            // 重置table，不然table展开时数据不刷新
            this.tableRefState = false
            setTimeout(() => {
                this.tableRefState = true
            }, 0)
            this.saveMapTableData(this.tableData, true)
            // 用来对比的初始数据
            // const temp = this.arrFieldConvert(val)
            // temp.forEach(item => {
            //     this.saveCloneMap(item)
            // })
            // 做完对比再置空
            this.wholeListData = {}
            // 初始化计算数量
            this.initCalNum('num')
        },
        // eslint-disable-next-line no-unused-vars
        async onload (row, treeNode, resolve) {
            let result
            if (row.children?.length > 0) {
                result = row.children
            } else {
                // 如果不是最子级，就从接口取
                if (!row.isAllLeaf) {
                    result = await this.getData(row.listId)
                } else {
                    // 是最子级，则初始为空，合并新增数据，并设为非最子级
                    result = []
                    // row.isLeaf = 0
                }
                // 如果有缓存数据，说明是点击的 “添加子级” 按钮
                if (this.addList.length > 0) {
                    result = result.concat(this.addList)
                    this.addList = []
                }
            }
            row.treeNode = treeNode
            row.resolve = resolve
            this.tableData.loadState = true
            this.$set(row, 'children', result)
            setTimeout(() => {
                delete this.tableData.loadState
            }, 200)
            // this.mapTableData[row.listId] = row
            // this.saveCloneMap(row)
            // result.forEach(item => {
            //     this.mapTableData[item.listId] = item
            //     this.saveCloneMap(item)
            // })
            // console.log('cloneMapInitTableData', this.cloneMapInitTableData)
            // console.log('this.mapTableData', this.mapTableData)
            // console.log('this.deleteTableData', this.deleteTableData)
            // result.forEach(item=>{
            //     if(row.unit !== '总额' && row.itemIsDetailed) {
            //         if(item.unitPrice !== row.unitPrice) {
            //             item.unitPrice = row.unitPrice
            //             this.onCalcAmount(item)
            //         }
            //     }
            // })
            // 结构初始数据
            if (row.isLeaf === 1) {
                // 和结构是同一个内存地址，新增项需要先删掉结构，否则新增的childrren和applyStructureList会互相指向
                this.$set(row, 'applyStructureList', JSON.parse(JSON.stringify(result)))
                // row.applyStructureList = result
            }
            resolve(result)
        },
        // 添加子级
        async addChilden (row, levelIsTotal) {
            if (!row.children) return
            // eslint-disable-next-line no-debugger
            // debugger
            row.isLeaf = 0
            row.price = ''
            // 删除结构
            for (let i = 0; i < row.children.length; i++) {
                if (row.children[i].label !== '项') {
                    row.children.splice(i--, 1)
                }
            }
            const uid = await this.uidBuilder({ num: 1 })
            // 项（第一层children）
            const addData = {
                amount: 0,
                applyStructureList: row.applyStructureList,
                children: [],
                hasChildren: true,
                billId: this.tenderId,
                changeType: 1,
                code: '', // 细目编码
                codeName: '', // 细目名称
                isAllLeaf: 0, // 是否所有最子级
                isLeaf: 1,
                isListLeaf: 0, // 是否是清单最子级
                isUpdateAmountState: false,
                isUpdateNumState: false,
                isUpdatePriceState: false,
                label: '项', // 标识
                listId: uid, // 本级id
                num: 0, // 数量
                packageId: this.packageId,
                parentId: row.listId, // 父级ID
                price: row.price,
                // priceType: 0,
                // recordId: '',
                unit: '' // 计量单位
            }
            // 增加项，没有结构或子级就无法新增
            if (row.children) row.children.push(addData)
            // 增加项里的结构（第二层childrren）
            const children = await this.addStructure(row, uid)
            this.$set(addData, 'children', children)
            this.saveMapTableData()
            let childrenHand = {}
            // 计算新加入行金额
            children.forEach(item => {
                childrenHand = this.mapTableData[item.listId]
                childrenHand.amount = Math.round(childrenHand.price * childrenHand.num)
            })
            // 向上汇总数量
            // eslint-disable-next-line no-unreachable
            this.recurCount({
                parentId: childrenHand.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                childrenHand,
                str: 'num',
                type: 'float'
            })
            if (levelIsTotal === false) {
                // 向上汇总金额
                this.recurCount({
                    parentId: childrenHand.parentId,
                    rootId: '0',
                    listField: 'listId',
                    parentField: 'parentId',
                    childrenHand,
                    str: 'amount'
                })
            }
            console.log('this.tableData', this.tableData)
        },
        // 添加子级（非生产性开支引入）
        async addChilden2 (row) {
            // if (!row.children) return
            // eslint-disable-next-line no-debugger
            // debugger
            row.isLeaf = 0
            row.hasChildren = true
            row.price = ''
            row.num = ''
            this.$set(row, 'children', [])
            // row.children = []
            // 删除结构
            // for (let i = 0; i < row.children.length; i++) {
            //     if (row.children[i].label !== '项') {
            //         row.children.splice(i--, 1)
            //     }
            // }
            const uid = await this.uidBuilder({ num: 1 })
            // 子级
            const addData = {
                amount: 0,
                // applyStructureList: row.applyStructureList,
                // children: [],
                // hasChildren: true,
                billId: this.tenderId,
                changeType: 1,
                code: '', // 细目编码
                codeName: '', // 细目名称
                isAllLeaf: 0, // 是否所有最子级
                isLeaf: 1,
                isListLeaf: 0, // 是否是清单最子级
                isUpdateAmountState: false,
                isUpdateNumState: false,
                isUpdatePriceState: false,
                // label: '项', // 标识
                listId: uid, // 本级id
                num: '', // 数量
                packageId: this.packageId,
                parentId: row.listId, // 父级ID
                price: ''
                // priceType: 0,
                // recordId: '',
                // unit: '' // 计量单位
            }
            row.children.push(addData)
            this.saveMapTableData()
        },
        onDelNode (row) {
            const callBack = () => {
                // 如果修改的是结构，修改父级的applyStructureList为-1
                if (row.structureName) {
                    this.mapTableData[row.parentId].applyStructureList.forEach(item => {
                        if (item.listId === row.listId) {
                            item.deleteState = 1
                        }
                    })
                }
                // 删除tableData与mapTableData
                const temp = row => {
                    if (row === undefined) return
                    // 父级的chilren
                    const siblings = this.mapTableData[row.parentId].children
                    // 在父级的chilren里删掉当前节点
                    const index = siblings.findIndex(item => {
                        if (item.listId === row.listId) {
                            // 不是新增数据变为-1
                            // if (row.changeType !== 1) {
                            // 删除映射表
                            // if (row.listId) {
                            //     delete this.mapTableData[row.listId]
                            // }
                            row.changeType = -1
                            // this.deleteTableData.push(row)
                            // }
                            // 向下寻找子级变为-1
                            const temp2 = row => {
                                while (row) {
                                    row = row.children
                                    if (!row) break
                                    // if(row===null) return
                                    if (Array.isArray(row)) {
                                        row.forEach(item => {
                                            // if (item.changeState !== 1) {
                                            item.changeState = -1
                                            // this.deleteTableData.push(item)
                                            // 删除映射表
                                            // if (item.listId) {
                                            //     delete this.mapTableData[item.listId]
                                            // }
                                            // }
                                            temp2(item)
                                        })
                                    }
                                }
                            }
                            temp2(row)
                            // 像上寻找父级变为2
                            const levelIds = getItemOfTreeArr(this.tableData, 'listId', item.listId)
                            for (let i = 0; i < levelIds.length - 1; i++) {
                                if (levelIds[i].changeType !== 1) {
                                    levelIds[i].changeType = 2
                                }
                            }
                            return true
                        }
                    })
                    siblings.splice(index, 1)
                    // 如果父级的长度为0则继续往上寻找删除
                    if (siblings.length === 0) {
                        // 如果顶级已经被删除，跳出
                        if (row === undefined) return
                        const level = this.mapTableData[this.mapTableData[row.parentId].listId]
                        temp(level)
                    }
                }
                temp(row)
                // 删除wholeListData
                if (Object.values(this.wholeListData).length !== 0) {
                    const row2 = this.wholeListData[row.listId]
                    console.log('row2', row2)
                    row2.changeState = -1
                    const temp2 = row => {
                        if (row === undefined) return
                        // console.log('row', row)
                        const _row = JSON.parse(JSON.stringify(row)) // 用来寻找上级
                        // 父级的chilren
                        const siblings = this.wholeListData[row.parentId].children
                        // 在父级的chilren里删掉当前节点
                        console.log('siblings', siblings)
                        const index = siblings.findIndex(item => {
                            if (item.listId === row.listId) {
                                console.log('执行了111')
                                // 不是新增数据变为-1
                                // if (row.changeState !== 1) {
                                // if (row.listId) {
                                //     // 删除映射表
                                //     // delete this.mapTableData[row.listId]
                                //     // 删除清单所有数据（已选功能）
                                //     // delete this.wholeListData[row.listId]
                                // }
                                row.changeState = -1
                                // wholeListData也要做改变，已选数据需要
                                // this.wholeListData[row.listId].changeState = -1
                                // this.deleteTableData.push(row)
                                // }
                                // 向下寻找子级变为-1
                                const temp2 = row => {
                                    while (row) {
                                        row = row.children
                                        if (!row) break
                                        // if(row===null) return
                                        if (Array.isArray(row)) {
                                            row.forEach(item => {
                                                // if (item.changeState !== 1) {
                                                item.changeState = -1
                                                // wholeListData也要做改变，已选数据需要
                                                // this.wholeListData[item.listId].changeState = -1
                                                // this.deleteTableData.push(item)
                                                // 删除映射表
                                                // if (item.listId) {
                                                //     delete this.mapTableData[item.listId]
                                                // }
                                                // 删除清单所有数据（已选功能）
                                                // delete this.wholeListData[row.listId]
                                                // }
                                                temp2(item)
                                            })
                                        }
                                    }
                                }
                                temp2(row2)
                            }
                        })
                        siblings.splice(index, 1)
                        // 如果父级的长度为0则继续往上寻找删除
                        if (siblings.length === 0) {
                            // console.log('000row', row)
                            // 如果顶级已经被删除，跳出
                            if (_row === undefined) return
                            const level =
                                this.wholeListData[this.wholeListData[_row.parentId].listId]
                            temp2(level)
                        }
                    }
                    temp2(row)
                }
                this.initCalNum('num')
                this.initCalNum('amount')
            }
            this.clientPop(
                'info',
                '是否删除选择的细目？删除是将本级及下级全部删除，请谨慎操作！',
                callBack
            )
        },
        // 输入后计划金额
        onCalcAmount (row) {
            row.amount = Math.round(row.num * row.price)
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'listId',
                parentField: 'parentId',
                row,
                str: 'amount'
            })
        },
        // 递归统计父级
        recurCount ({ parentId, rootId, listField, parentField, row, str, type = 'int' }) {
            const parent = this.mapTableData[parentId]
            console.log('parent', parent)
            // console.log('str', str)
            // console.log('parent', parent)
            // console.log('name', parent.label, parent.code)
            // console.log('this.mapTableData', this.mapTableData)
            // 统计所有同级
            const countSibling = parent.children.reduce((prev, item) => {
                if (type === 'int') {
                    return prev + Math.round(item[str])
                } else {
                    console.log('item[str]', item[str])
                    return prev + parseFloat(parseFloat(item[str]).toFixed(4))
                }
            }, 0)
            // console.log('countSibling', countSibling)
            // 赋值汇总数据给父级
            parent[str] = countSibling // 赋值汇总数据给父级
            // 到根节点
            if (parentId === rootId) {
                return
            }
            // 未到根节点则继续遍历父节点
            return this.recurCount({
                parentId: parent[parentField],
                rootId,
                listField,
                parentField,
                row,
                str,
                type: str === 'num' ? 'float' : 'int'
            })
        },
        tableRowClassName ({ row }) {
            // 删除显示优先级最高放前面
            if (row.state === -1 || row.changeType === -1 || row.changeType === -2) {
                return 'red'
            } else if (row.state === 1) {
                return 'green'
            } else if (row.state === 2) {
                return 'yellow'
            }
        },
        async uidBuilder (params, type = 'str') {
            let temp = []
            await uidBuilder(params).then(res => {
                temp = type === 'str' ? res[0] : res
            })
            return temp
        }
        // refreshLoadTree (parentId) {
        //     // 根据父级id取出对应节点数据
        //     // const { row, treeNode, resolve } = this.mapTableData[parentId]
        //     let children = this.mapTableData[parentId].children
        //     const tableRef = this.$refs.tableRef
        //     this.$set(tableRef.store.states.lazyTreeNodeMap, parentId, children)
        // },
    }
}
</script>
<style lang="scss" scoped>
::v-deep .hide-icon {
    .el-table__expand-icon {
        display: none;
    }
}
::v-deep.el-table__row {
    .cell {
        display: flex;
        align-items: center;
    }
    td:nth-child(6),
    td:nth-child(7),
    td:nth-child(8) {
        .cell {
            justify-content: flex-end;
        }
    }
}
::v-deep .el-popover__reference-wrapper {
    display: flex;
    height: 100%;
}
.ruleMessage {
    margin-bottom: 10px;
    margin-left: 10px;
    color: red;
}

.e-table {
    background: #fff;
}
</style>
